using AutoMapper;
using bookmeetingroom.Data;
using bookmeetingroom.Data.Entities;
using bookmeetingroom.Helper;
using bookmeetingroom.Models;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace bookmeetingroom.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Produces("application/json")]
    [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "Admin")]
    public class UserController : ControllerBase
    {
        private readonly ApplicationDbContext _dbContext;
        private readonly ILogger<BuildingController> _logger;
        private readonly IMapper _mapper;
        private readonly UserManager<ApplicationUser> _userManager;

        public UserController(ApplicationDbContext dbContext, UserManager<ApplicationUser> userManager,
        ILogger<BuildingController> logger, IMapper mapper)
        {
            _dbContext = dbContext;
            _logger = logger;
            _mapper = mapper;
            _userManager = userManager;
        }
        [HttpGet]
        public ActionResult List(string username, string email, string phonenumber, int pagesize, int currentPage)
        {
            Guid guid = this.User.GetCompanyID();
            var users = _dbContext.Users
            .Where(n => string.IsNullOrEmpty(username) || n.UserName.Contains(username))
            .Where(n => string.IsNullOrEmpty(email) || n.Email.Contains(email))
            .Where(n => string.IsNullOrEmpty(phonenumber) || n.PhoneNumber.Contains(phonenumber))
            .Where(n => n.CompanyId == guid)
            .OrderByDescending(n => n.CreatedTime).Skip((currentPage - 1) * pagesize).Take(pagesize).ToArray();

            return Ok(new { message = "", data = users });

        }

        [HttpPost]
        public async Task<ActionResult> Save(UserModel user)
        {
            Guid companyID = this.User.GetCompanyID();

            if (!ModelState.IsValid)
                return BadRequest(ModelState.GetErrorMessages());

            if (user.Id <= 0)
            {
                var applicationUser = new ApplicationUser
                {
                    CompanyId = companyID,
                    EmailConfirmed = true,
                    LockoutEnabled = false
                };


                await _userManager.CreateAsync(applicationUser, user.Password);
            }
            else
            {
                var applicationUser = _dbContext.Users.Find(user.Id);
                applicationUser.Email = user.Email;
                applicationUser.PhoneNumber = user.PhoneNumber;
                applicationUser.FullName = user.FullName;
                applicationUser.PasswordHash = _userManager.PasswordHasher.HashPassword(applicationUser, user.Password);
                await _userManager.UpdateAsync(applicationUser);



            }

            return Ok(new { message = (user.Id <= 0) ? "建立成功" : "修改成功" });

        }
        [HttpGet("{username}")]
        public async Task<ActionResult> Detail(string username)
        {
            var user = await _dbContext.Users.Where(n => n.UserName == username)
                .SingleOrDefaultAsync();

            return Ok(new { message = "", data = user });
        }
        [HttpPost("Remove/{username}")]
        public async Task<ActionResult> Remove(string username)
        {
            if (string.IsNullOrEmpty(username)) return BadRequest("不能找到此用户");

            var user = await _dbContext.Users.Where(n => n.UserName == username)
                           .SingleOrDefaultAsync();

            var result = await _userManager.DeleteAsync(user);

            if (result.Succeeded)
            {
                return Ok(new { message = "删除成功" });

            }
            else
            {
                var error = string.Join(",", result.Errors.Select(n => n.Description).ToArray());

                return BadRequest(error);

            }


        }

    }
}
